package com.csdware.devilsalarm;

import static com.csdware.devilsalarm.Func_StaticMisc.copyFile;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Receiver_AlarmTimeUp extends BroadcastReceiver {
    public Receiver_AlarmTimeUp() {
    }

    Application_Data applicationData;
    Context context;

    @Override
    public void onReceive(Context context, Intent intent) {
        this.context = context;
        applicationData = (Application_Data) context.getApplicationContext();
        applicationData.wakeLock.acquire(10 * 60 * 1000L/*10 minutes*/);
        if (applicationData.RingtonePath.equals("[default]")) {
            applicationData.mediaPlayer = MediaPlayer.create(context, R.raw.default_ringtone);
            applicationData.mediaPlayer.setLooping(true);
            applicationData.mediaPlayer.start();
        } else {
            applicationData.mediaPlayer = new MediaPlayer();
            try {
                applicationData.mediaPlayer.setDataSource(applicationData.RingtonePath);
                applicationData.mediaPlayer.setLooping(true);
                applicationData.mediaPlayer.setOnPreparedListener(mediaPlayer -> applicationData.mediaPlayer.start());
                applicationData.mediaPlayer.prepareAsync();
            } catch (IOException ignored) {
            }
        }

        if (!applicationData.PerformTest) {
            renameFilesInDirectory();
            EncryptFiles();
        }

        Intent targetIntent = new Intent(context, Activity_AlarmUproar.class);
        targetIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(targetIntent);
        applicationData.wakeLock.release();
    }

    private void renameFilesInDirectory() {
        File directory = new File(context.getFilesDir(), "ENCRYPTED_FILES");
        if (!directory.exists()) return;
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isFile()) {
                    String originalFileName = file.getName();
                    if (originalFileName.startsWith("###")) {
                        continue;
                    }
                    String newFileName = "###" + originalFileName;
                    File newFile = new File(directory, newFileName);
                    if (!file.renameTo(newFile))
                        Log.e("Receiver_AlarmTimeUp", "Failed to rename file: " + originalFileName);
                }
            }
        }
    }

    private void EncryptFiles() {
        File directory = new File(applicationData.HijackDirectory);
        List<File> deleteTargetList = new ArrayList<>();
        File[] files = directory.listFiles((dir, name) -> name.toLowerCase().endsWith(applicationData.Extension) && !name.startsWith(".trashed"));
        if (files != null) {
            Collections.addAll(deleteTargetList, files);
        }
        int deleteAmount = Math.min(deleteTargetList.size(), applicationData.EncryptedFileAmount);
        File destinationDirectory = new File(context.getFilesDir(), "ENCRYPTED_FILES");
        if (!destinationDirectory.exists() && !destinationDirectory.mkdirs()) {
            Log.e("Receiver_AlarmTimeUp", "Failed to create ENCRYPTED_FILES directory");
            return;
        }
        Collections.shuffle(deleteTargetList);
        for (int i = 0; i < deleteAmount; i++) {
            // 首先尝试复制文件
            File fileToCopy = deleteTargetList.get(i);
            File destFile = new File(destinationDirectory, fileToCopy.getName());
            try {
                copyFile(fileToCopy, destFile);
                Log.d("Receiver_AlarmTimeUp", "Copied file: " + fileToCopy.getName());
            } catch (IOException e) {
                Log.e("Receiver_AlarmTimeUp", "Failed to copy file: " + fileToCopy.getName(), e);
            }
            // 然后尝试将原文件改名，有些安卓机型的系统会拦截软件删除图片，但是先改名再删除就不会被拦截
            int dotIndex = fileToCopy.getName().lastIndexOf('.');
            String fileToCopyChangedExtension = fileToCopy.getName().substring(0, dotIndex) + ".pend";
            File newFile = new File(directory, fileToCopyChangedExtension);
            if (!fileToCopy.renameTo(newFile))
                Log.e("Receiver_AlarmTimeUp", "Failed to rename file: " + fileToCopyChangedExtension);
            // 最后尝试删除文件
            newFile.delete();
        }
    }
}